package mr.zhang.shiro;

import mr.zhang.pojo.UserBean;
import mr.zhang.service.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Created by jerry on 15/2/16.
 * E-mail:huaxinxc@me.com
 */
@Service
@Transactional
public class RoleShiro extends AuthorizingRealm {

    Logger log = LoggerFactory.getLogger(RoleShiro.class);
    @Resource(name = "adminService")
    private AdminService adminService;

    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }

    public RoleShiro() {
        log.info("======== AAAA  =========");
        setName("roleShiro");
    }

    // private realm;

    /**
     * 权限验证 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // get login name
        String loginName = (String) principalCollection.fromRealm(getName()).iterator().next();

        System.out.println(loginName + "执行到这里！");

        // do database
        UserBean userBean = new UserBean();
        userBean.setUsername("admin");
        userBean.setPassword("admin");
        userBean.setId(1);

        return null;
    }

    /**
     * 登陆验证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // UserBean user = adminService.adminTest(token.getUsername());
        UserBean userBean = new UserBean();
        userBean.setUsername("admin");
        userBean.setPassword("admin");
       // userBean.setRolecode("admin");
        userBean.setId(1);

        if (userBean != null) {

            log.info("role sys ======>>>" +token.getUsername() +"\t" +token.getPassword().toString());

            return new SimpleAuthenticationInfo(userBean.getId(),userBean.getUsername(), userBean.getPassword());

        } else {
            log.info("权限错误");
            return null;
        }
    }
}
